import difflib
import json
import sys

import Levenshtein as Levenshtein

from project_list import project_list as popular_project_list


def name_detect(project_name):
    # project_list = []
    # pypi_json = open('Include/top-pypi-packages-365-days.json', 'r', encoding='utf-8')
    # pypi_dict = json.loads(pypi_json.read())
    # for project_dict in pypi_dict['rows']:
    #     project_list.append(project_dict['project'])
    # print(project_list)
    typo_project_list = []
    for popular_project_name in popular_project_list:
        # seq = difflib.SequenceMatcher(None, project_name, project)
        # ratio = seq.ratio()
        if popular_project_name == project_name:
            return []
        new_popular_project_name = popular_project_name.replace('-', '').replace('_', '').replace('python', 'py')
        new_project_name = project_name.replace('-', '').replace('_', '').replace('python', 'py')
        if new_popular_project_name == new_project_name:
            typo_project_list.append(popular_project_name)
            continue
        ratio = Levenshtein.ratio(project_name, popular_project_name)
        if ratio >= max(0.8, 1 - (1 / len(popular_project_name))):
            typo_project_list.append(popular_project_name)
    return typo_project_list


name = sys.argv[1]
typo_project_list = name_detect(name)
if len(typo_project_list) > 0:
    if len(typo_project_list) == 1:
        print('Package %s may have typosquatting with package %s!!!' % (name, typo_project_list[0]))
    elif len(typo_project_list) > 1:
        print('Package %s may have typosquatting with %s packages!!!' % (name, len(typo_project_list)))
        print('There are the following packages:')
        for typo_project in typo_project_list:
            print(typo_project)
